package com.study.thread;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;

/**
 * @description 消费者
 * @author hw
 * @date 2022/1/2 18:01:30
 */
@Data
public class ConsumerThread implements Runnable{

    Logger logger = LoggerFactory.getLogger(ConsumerThread.class);

    //包
    private Queue<String> bags;

    //限定包的数量
    private int maxSize;

    @Override
    public void run() {
        //循环
        while (true){
            synchronized (bags){
                while (bags.size() == 0){
                    try {
                        logger.info("bags为空, 等待生产...");
                        bags.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //睡一秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //消费
                String bag = bags.remove();
                //打印
                logger.info("消费了一个包: " + bag);
                //唤醒生产者
                bags.notifyAll();
            }
        }
    }
}
